package com.gitee.zycra.union.api.dao;

import com.gitee.zycra.jdbc.common.BaseDao;
import com.gitee.zycra.jdbc.common.CommonSelector;
import com.gitee.zycra.union.api.common.model.ApiProject;
import com.gitee.zycra.union.api.common.vo.ProjectDetailVO;
import com.gitee.zycra.union.api.common.vo.ProjectVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author zycra
 */
@Repository
public class ApiProjectDao extends BaseDao<ApiProject> {

    @Autowired
    private CommonSelector commonSelector;

    /**
     * 添加项目
     *
     * @param apiProject 项目对象
     * @return 影响行数
     */
    public int insert(ApiProject apiProject) {
        return insertIntoTable(apiProject);
    }

    /**
     * 更新项目
     *
     * @param apiProject 项目对象
     * @return 影响行数
     */
    public int updateById(ApiProject apiProject) {
        return updateTableById(apiProject);
    }

    /**
     * 更新项目
     *
     * @param apiProject 项目对象
     * @return 影响行数
     */
    public int updateByIdAndGroupId(ApiProject apiProject) {
        return getJdbcTemplate().update("UPDATE api_project SET project_name = ?, project_label = ?, project_host = ? WHERE id = ? AND group_id = ?",
                apiProject.getProjectName(), apiProject.getProjectLabel(), apiProject.getProjectHost(), apiProject.getId(), apiProject.getGroupId());
    }

    /**
     * 根据ID删除项目
     *
     * @param groupId 项目组ID
     * @param id      项目ID
     * @return 更新结果
     */
    public int updateToDelete(Long groupId, Long id) {
        return getJdbcTemplate().update("UPDATE api_project SET deleted = 1 WHERE id = ? AND group_id = ?", id, groupId);
    }

    /**
     * 根据项目组ID查询项目
     *
     * @param groupId 项目组ID
     * @return 项目组下所有项目
     */
    public List<ProjectVO> selectByGroupId(Long groupId) {
        return commonSelector.selectByParam(getJdbcTemplate(),
                "SELECT id, project_name FROM api_project WHERE group_id = ? AND deleted = 0", ProjectVO.class, List.of(groupId));
    }

    /**
     * 根据项目ID查询项目
     *
     * @param groupId 项目组ID
     * @param id      项目ID
     * @return 项目
     */
    public ProjectDetailVO selectProjectDetailById(Long groupId, Long id) {
        return commonSelector.selectOneByParam(getJdbcTemplate(),
                "SELECT id, project_name, project_label, project_host FROM api_project WHERE id = ? AND group_id = ?",
                ProjectDetailVO.class, List.of(id, groupId));
    }
}
